package com.yinp.proapp.module.customview.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.yinp.proapp.R;
import com.yinp.proapp.utils.AppUtils;

/**
 * @author :yinpeng
 * date      :2021/8/23
 * package   :com.yinp.proapp.module.customview.view
 * describe  :
 */
public class PeculiarView extends LinearLayout {
    public PeculiarView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public PeculiarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private Paint paintContent;
    private Path pathContent;//整体的路径
    private Path pathCircle;//圆的路径
    private int bgColor;//背景颜色
    private int conner;//圆角
    private int radius;//圆的半径
    private int circleDx;//圆左移右移的距离
    private int height;
    private int width;
    private boolean isFirst;

    private void init(Context context, AttributeSet attrs) {
        paintContent = new Paint();
        paintContent.setStyle(Paint.Style.FILL);
        paintContent.setColor(Color.WHITE);

        pathContent = new Path();
        pathCircle = new Path();

        setBackgroundColor(Color.TRANSPARENT);
        setWillNotDraw(false);
        isFirst = true;

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.PeculiarView);

        bgColor = array.getColor(R.styleable.PeculiarView_peculiarColor, 0);
        conner = array.getInteger(R.styleable.PeculiarView_peculiarCorners, 0);
        radius = array.getInteger(R.styleable.PeculiarView_peculiarCircleRadius, 0);
        circleDx = array.getInteger(R.styleable.PeculiarView_peculiarCircleDx, 4);

        array.recycle();

        conner = (int) AppUtils.dpToPx(conner);
        radius = (int) AppUtils.dpToPx(radius);
        circleDx = (int) AppUtils.dpToPx(circleDx);
        if (bgColor != -1) {
            paintContent.setColor(bgColor);
        }
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (isFirst) {
            isFirst = false;
            width = getWidth();
            height = getHeight();
            pathContent.addRoundRect(0, 0, width, height, conner, conner, Path.Direction.CCW);
            pathCircle.addCircle(-circleDx, height / 2, radius, Path.Direction.CCW);
            pathCircle.addCircle(width + circleDx, height / 2, radius, Path.Direction.CCW);
            pathContent.op(pathCircle, Path.Op.XOR);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPath(pathContent, paintContent);
    }
}
